<?php

namespace App\Services\BrokerageDivider;

use Carbon\Carbon;
use App\Models\User;
use Brick\Math\RoundingMode;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BrokerageCashier
{
	/**
	 * @var User
	 */
	protected $user;
	
	protected function setUser(User $user)
	{
		$this->user = $user;
	}
	
	protected function getOrderBrokerage()
	{
		return $this->user->brokerages()
			->where('remark', 'pay_order')
			->whereNull('settled_at')
			->whereNull('disabled_at')
			->whereDate('created_at', '<', Carbon::today()->day(1));
	}
	
	protected function getVipBrokerage()
	{
		return $this->user->brokerages()
			->where('remark', 'pay_vip_purchase')
			->whereNull('settled_at')
			->whereNull('disabled_at')
			->whereDate('created_at', '<', Carbon::today()->day(1));
	}
	
	public function settle(User $user)
	{
		$this->setUser($user);
		
		DB::transaction(function () {
			
			$orderBrokerage = $this->getOrderBrokerage();
			$orderMoney = big_decimal($orderBrokerage->sum('money'));

			$orderBrokerage->update(['settled_at' => Carbon::now()]);
			
			
			$vipBrokerage = $this->getVipBrokerage();
			$vipMoney = big_decimal($vipBrokerage->sum('money'));
			
			$vipBrokerage->update(['settled_at' => Carbon::now()]);
			
			$brokerage = $orderMoney->plus($vipMoney)->toScale(2, RoundingMode::HALF_UP);
			
			if ($brokerage->isLessThanOrEqualTo(0)) return;
			
			$money = big_decimal($brokerage);
			$updatingBrokerage = $money->plus($this->user->dividend_brokerage);
			$this->user->update(['dividend_brokerage' => $updatingBrokerage->toScale(2, RoundingMode::HALF_UP)]);
		});
	}
}
